import AuthAPI from "@/api/auth";
import { defineStore } from "pinia";
import { ref } from "vue";
import router from "../../router";

export const useUserStore = defineStore("user", () => {
  
  var user = ref({
    roles: [],
    perms: [],
  });

  function login(data) {
    return new Promise((resolve, reject) => {
      AuthAPI.Login(data)
        .then((res) => {
          user.value = res.user;
          localStorage.setItem("token", res.token);
          localStorage.setItem("user", JSON.stringify(res.user));
          resolve(res.user);
        })
        .catch((err) => {
          reject(err);
          console.log("login err", err);
        });
    });
  }

  function logout() {
    AuthAPI.logout().then(res=>{
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      location.reload();
      router.replace({path: "/login"});
    })
  }

  return { user, login, logout };
});
